// components/upload/index.js
const Upload = require("../../libs/upload.js");
const app = getApp()

Component({
  lifetimes:{
    attached: function () {
      // 在组件实例进入页面节点树时执行
      // let uploader = new Upload(this.data.options);
      // this.setData({
      //   uploader: uploader
      // });
    },
  },
  /**
   * 组件的属性列表
   */
  properties: {
    uploadType:{
      type: [Number, String],
      value: 1//1:上传图片2:上传视频 默认图片上传
    },
    options:{
      type:Object,
      value:{
        dir:"",
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    uploader:null,
    fileList:[]
  },

  /**
   * 组件的方法列表
   */
  methods: {
    choose(){
      const uploadFactory = {
        1:"chooseImage",
        2:"chooseVideo"
      }
      this[uploadFactory[this.data.uploadType]]();
    },
    chooseVideo(){
      console.log("======选择视频==========")
      wx.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 60,
        camera: 'back',
        success:(res) =>{
          console.log(res);
          const tempFilePath = res.tempFilePath;
          let cover = res.thumbTempFilePath;
          let uploader = new Upload(Object.assign({
            OSSAccessKeyId: app.globalData.$config.VIDEO_OSS_ACCESS_ID,
            AccessKeySecret: app.globalData.$config.VIDEO_OSS_ACCESS_SECRET
          },this.data.options));
          let config = uploader.generateConfig();
          let name = new Date().getTime() + Math.floor(Math.random() * 150);
          let dir = this.data.options.dir ? `${this.data.options.dir}/` : "";
          let aliyunFileKey = `${dir}${name}.mp4`;
          let data = {
            ...config,
            key: aliyunFileKey,
            name
          }
          this.uploadSubmit(app.globalData.$config.VIDEO_BUCKET_URL, tempFilePath, data);
        },
        fail:(err)=>{
          wx.showToast({
            title: '取消选择视频',
            icon:"none"
          })
        }
      })
    },
    chooseImage() {
      console.log("=======开始选择图片==========");
      wx.chooseImage({
        count: 9,
        sizeType: ["original", "compressed"],
        success: (res) => {
          const tempFilePaths = res.tempFilePaths || [];
          let uploader = new Upload(this.data.options);
          let config = uploader.generateConfig();
          let dir = this.data.options.dir ? `${this.data.options.dir}/` : app.globalData.$config.IMAGE_OSS_URL;
          //适配多图上传
          tempFilePaths.map(v => {
            let name = new Date().getTime() + Math.floor(Math.random() * 150);
            let aliyunFileKey = `${dir}${name}.jpg`;
            let data = {
              ...config,
              key: aliyunFileKey,
              name
            }
            this.uploadSubmit(app.globalData.$config.IMAGE_BUCKET_URL, v, data);
          })
        },
        fail: (res) => {
          wx.showToast({
            title: '取消选择图片',
            icon:"none"
          })
        }
      })
    },
    deleteRecord(e){
      let idx = e.target.dataset.idx;
      this.data.fileList.splice(idx,1);
      this.updateFileList();
    },
    uploadSubmit(url,path,data){
      wx.showLoading({
        title: "上传中……"
      });
      wx.uploadFile({
        url: url,
        filePath: path,
        name: "file",
        formData: {
          ...data
        },
        success: (res) => {
          console.log(res);
          if (res.statusCode == 200) {
            wx.showToast({
              title: '上传成功',
              icon: "none"
            });
            let urlPath = `${url}${data.key}`;
            this.data.fileList.push({
              name:data.name,
              url: urlPath,
              // cover: app.globalData.$config.VIDEO_BUCKET_VIEW_URL+data.name+".jpg"
              cover: `${urlPath}?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast`
            })
            //let timer = setTimeout(()=>{
              this.updateFileList();
              //console.log("update fileList");
              //clearTimeout(timer);
            //},5000)
          } else {
            wx.showToast({
              title: '上传失败',
              icon: "none"
            })
          }
        },
        complete: () => {
          wx.hideLoading();
        }
      })
    },
    updateFileList(){
      this.setData({
        fileList: this.data.fileList
      })
      this.triggerEvent("change", {
        fileList: this.data.fileList
      });
    }
  }
})
